#include "MysqlConnector.h"
#include "MysqlSession.h"

#include <chrono>
#include <iostream>
#include <memory>
#include <thread>

#define GLOG_USE_GLOG_EXPORT
#include <glog/logging.h>

using namespace std;

std::shared_ptr<MysqlConnector> g_mysqlConnector;

void mysqlInsertTaskThread()
{
    std::thread::id tid     = std::this_thread::get_id();
    auto            session = g_mysqlConnector->getSession();
    if (!session) {
        LOG(WARNING) << tid << "get session failed!";
        return;
    }

    auto schema = session->getSchema("test_database");
    if (!schema) {
        LOG(WARNING) << tid << "get schema failed!";
        return;
    }

#if 0
    std::list<mysqlx::DbDoc> docs = {
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
        mysqlx::DbDoc(R"({"name" : "hello"})"),
    };

    mysqlx::Collection myColl = schema->createCollection("test_collection", true);
    auto               bTime  = std::chrono::system_clock::now();
    for (int i = 0; i < 10; i++) {
        // myColl.add(R"({"name" : "hello"})").execute();
        myColl.add(docs).execute();
        auto eTime = std::chrono::system_clock::now();
        LOG(INFO) << tid << " insert 操作耗时: " << std::chrono::duration<double, std::ratio<1, 1000>>(eTime - bTime).count();
        bTime = eTime;
    }
#else

    std::list<mysqlx::Row> rows;
    for (int i = 0; i < 10; i++) {
        mysqlx::Row row;
        row.set(0, "hello");
        row.set(1, "world");
        rows.push_back(row);
    }
    mysqlx::Table table = schema->getTable("test_table");
    table.insert("name", "type").rows(rows).execute();

#endif
}

int main(int argc, char *argv[])
{
    g_mysqlConnector = std::make_shared<MysqlConnector>("develop:password@10.100.72.95");

    int                          max_run_thread = 10;
    std::shared_ptr<std::thread> th[max_run_thread];

    auto bTime = std::chrono::system_clock::now();
    for (int i = 0; i < max_run_thread; i++) {
        th[i].reset(new std::thread(&mysqlInsertTaskThread));
    }
    for (int i = 0; i < max_run_thread; i++) {
        if (th[i] && th[i]->joinable()) {
            th[i]->join();
        }
    }
    auto eTime = std::chrono::system_clock::now();
    LOG(INFO) << "总耗时: " << std::chrono::duration<double, std::ratio<1, 1000>>(eTime - bTime).count() << "ms";

    return 0;
}